package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.mappers.OrderMapper;
import cn.tedu.mall.order.service.IOmsOrderService;
import cn.tedu.mall.pojo.order.dto.OrderListTimeDTO;
import cn.tedu.mall.pojo.order.dto.OrderStateUpdateDTO;
import cn.tedu.mall.pojo.order.vo.OrderDetailVO;
import cn.tedu.mall.pojo.order.vo.OrderListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements IOmsOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserInfo userInfo;
    @Override
    public void updateOrderState(OrderStateUpdateDTO orderStateUpdateDTO) {

    }

    @Override
    public JsonPage<OrderListVO> listOrdersBetweenTimes(OrderListTimeDTO orderListTimeDTO) {
        // 对参数的日期时间做一下格式化,有错误抛异常,没错误校验,订正添加默认时间
        formatTimeValidAndReplenish(orderListTimeDTO);
        // 获取userId
        Long userId = userInfo.getUserId();
        orderListTimeDTO.setUserId(userId);
        System.out.println(orderListTimeDTO);
        // 开启分页查询
        PageHelper.startPage(orderListTimeDTO.getPage(), orderListTimeDTO.getPageSize());
        List<OrderListVO> orderListVO = orderMapper.selectOrdersBetweenTimes(orderListTimeDTO);
        return JsonPage.restPage(new PageInfo<>(orderListVO));
    }

    @Override
    public OrderDetailVO getOrderDetail(Long id) {
        return null;
    }

    private void formatTimeValidAndReplenish(OrderListTimeDTO orderListTimeDTO) {
        //检查时间是否满足startTime<endTime
        LocalDateTime start = orderListTimeDTO.getStartTime();
        LocalDateTime end = orderListTimeDTO.getEndTime();
        if (start != null && end != null) {
            //起始时间必须小于结束时间
            if (start.toInstant(ZoneOffset.of("+8")).toEpochMilli() > end.toInstant(ZoneOffset.of("+8")).toEpochMilli()) {
                throw new CoolSharkServiceException(ResponseCode.CONFLICT, "查询订单时间段不正确,起始时间应该早于结束时间");
            }
        }
        //补充非空
        if (start == null || end == null) {
            //填写默认值,最近一个月订单情况
            end = LocalDateTime.now();
            start = end.minusMonths(1);
            orderListTimeDTO.setStartTime(start);
            orderListTimeDTO.setEndTime(end);
        }
    }
}
